package main

import (
	"fmt"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
)

func RegisterEmailRouter(r *gin.Engine, inboxPoolService *InboxPoolService) {
	group := r.Group("/email")
	{
		group.GET("/message/list", func(c *gin.Context) { getEmailMessageList(c, inboxPoolService) })
	}
}

type EmailCache struct {
	data   []*EmailMessage
	expire time.Time
}

type EmailCachePool struct {
	mu    sync.RWMutex
	cache map[string]EmailCache
}

var emailCachePool = EmailCachePool{
	cache: make(map[string]EmailCache),
}

// 获取邮件列表
// @Summary 获取邮件列表
// @Description 根据 user 和 password 获取邮件列表
// @Tags email
// @Accept json
// @Produce json
// @Param user query string true "用户名"
// @Param password query string true "密码"
// @Success 200 {array} EmailMessage "邮件列表"
// @Router /email/message/list [get]
func getEmailMessageList(c *gin.Context, inboxPoolService *InboxPoolService) {
	user := c.Query("user")
	password := c.Query("password")
	if user == "" || password == "" {
		_ = c.Error(fmt.Errorf("参数 user 与 password 必填"))
		return
	}

	// 缓存键
	key := user + ":" + password

	// 先读缓存
	emailCachePool.mu.RLock()
	entry, ok := emailCachePool.cache[key]
	emailCachePool.mu.RUnlock()
	if ok && time.Now().Before(entry.expire) {
		// 命中缓存，直接返回
		c.JSON(200, entry.data)
		return
	}

	inbox := inboxPoolService.GetInbox(user, password)
	err := inbox.inboxService.Connect()
	if err != nil {
		_ = c.Error(err)
		return
	}

	defer inbox.inboxService.Close()
	list, err := inbox.inboxService.MessageList()
	if err != nil {
		_ = c.Error(err)
		return
	}

	// 写入缓存，生存时间 10 秒
	emailCachePool.mu.Lock()
	emailCachePool.cache[key] = EmailCache{
		data:   list,
		expire: time.Now().Add(10 * time.Second),
	}
	emailCachePool.mu.Unlock()

	c.JSON(200, list)
}
